#!/usr/bin/env python
#
# Copyright 2009 Liu, Xiaokang <4341322@gmail.com>
# Blog <http://www.ioio.name/>
#
import logging
import wsgiref.handlers
from google.appengine.api import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch

from handlestory import Parse 


class Test(webapp.RequestHandler):
    def get(self):
        taskqueue.add(url='/work', params={'url': 'http://www.nuoqiu.com/static/5630/1216064.html'})
        self.response.out.write('OK')


class StoryWork(webapp.RequestHandler):
    def get(self):
        #self.response.out.write('Are Your Site is uptime now?')
        logging.info('get')
        #url = self.request.get('url')
        #self._fetch(handle_result,url)
    def post(self):
        url = self.request.get('url')
        type = self.request.get('type')
        text = self.handle_result(url)
        t = Parse(text).parse_story()
        self.response.out.write(t)
        
    def handle_result(self,url):
        try:
            result = urlfetch.fetch(url,deadline=10)
            if result.status_code == 200:
                text = result.content
                #logging.info(str(text))
        except urlfetch.InvalidURLError:
                logging.info('InvalidURLError')
            
        except urlfetch.ResponseTooLargeError:
                logging.info('ResponseTooLargeErrorget_reslut() failure')

        except urlfetch.DownloadError:
                logging.info('DownloadError get_reslut() failure')
        return text
        
    
        
application = webapp.WSGIApplication([
    ('/',Test),
    ('/work', StoryWork),
], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
